package com.boful.convert.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.time.DurationFormatUtils;

public class TimeLengthUtils {
	/**
	 * 转换成秒
	 * 
	 * @param src
	 *            源字符串(格式：HH:MM:SS);
	 * @return
	 */
	public static long StringToNumber(String src) {
		try {
			String[] values = src.split(":");
			long hour = 0;
			long minute = 0;
			long seconds = 0;
			if (values.length == 3) {
				hour = Integer.parseInt(values[0]) * 60 * 60;
				minute = Integer.parseInt(values[1]) * 60;
				seconds = (long) Double.parseDouble(values[2]);
			} else if (values.length == 2) {
				minute = Integer.parseInt(values[0]) * 60;
				seconds = (long) Double.parseDouble(values[1]);
			} else if (values.length == 1) {
				seconds = (long) Double.parseDouble(values[0]);
			}

			return (hour + minute + seconds);
		} catch (Exception e) {
			return -1;
		}

	}

	public static String NumberToString(long time) {
		return DurationFormatUtils.formatDuration(time * 1000, "HH:mm:ss");
	}

	public static String formatTime(String time) {
		String[] values = time.split(":");
		long hour = 0;
		long minute = 0;
		long seconds = 0;
		if (values.length == 3) {
			hour = Integer.parseInt(values[0]);
			minute = Integer.parseInt(values[1]);
			seconds = (long) Double.parseDouble(values[2]);
		} else if (values.length == 2) {
			minute = Integer.parseInt(values[0]);
			seconds = (long) Double.parseDouble(values[1]);
		} else if (values.length == 1) {
			seconds = (long) Double.parseDouble(values[0]);
		}
		StringBuffer buffer = new StringBuffer();
		if (hour == 0) {
			if (minute == 0) {
				buffer.append(seconds + "秒");
			} else {
				buffer.append(minute + "分" + seconds + "秒");
			}
		} else {
			buffer.append(hour + "时" + minute + "分" + seconds + "秒");
		}
		return buffer.toString();

	}

	/***
	 * 分割时间段
	 * 
	 * @param total
	 *            总时长
	 * @param len
	 *            分割的段数
	 * @return [[startTime,endTime],[startTime,endTime],[startTime,endTime]....]
	 */
	public static List<List<Long>> splitTime(long total, int len) {
		List<List<Long>> result = new ArrayList<>();

		if (total > 0 && len >= 0) {
			if (len == 0) {
				List<Long> tmp = new ArrayList<>();
				tmp.add(0L);
				tmp.add(total);
				result.add(tmp);
				return result;
			} else {

				// 每段时长
				long per = total / len;

				for (int i = 0; i < len; i++) {
					long startTime = i * per;
					long endTime = startTime + per;

					endTime = endTime > total ? total : endTime;
					endTime = endTime - 1;
					if (i == len - 1) {
						if (endTime < total) {
							endTime = total;
						}
					}

					List<Long> tmp = new ArrayList<Long>();
					tmp.add(startTime);
					tmp.add(endTime);
					result.add(tmp);
				}
				return result;
			}
		}

		return result;
	}
}
